from socialbar.barManagerControl import isCurrentBar  
from socialbar.models import Bar, Deal
from socialbar.constants import DEALSSTATUS, keyFromValue
from django.views.generic.simple import direct_to_template
import logging


def main(request):
  if 'action' in request.POST and request.POST['action'] == 'validate':
    logging.debug('Validating id = ' + request.POST['id'])
    deal = Deal.objects.get(id = request.POST['id'])
    if deal is None:
      logging.debug('Functional Error : No deal found to validate.')
      return direct_to_template(request, 'barManager/cuponManager.html',
          {'error' : 'NoDealFound'})
    if isCurrentBar(deal.bar, request) is False:
      logging.debug('Functional Error : Wrong bar logged for validation.')
      return direct_to_template(request, 'barManager/cuponManager.html',
          {'error' : 'WrongBarLogged'})
    deal.status = keyFromValue(DEALSSTATUS, 'Validate')
    deal.save()
  
  bars = Bar.objects.filter(adminLogin = request.user)
  if len(bars) == 0:
    logging.debug('Functional Error : Staff user is not associated with a bar account.')
    return direct_to_template(request, 'barManager/cuponManager.html',
        {'error' : 'NoBarAssociated'})
  bar = bars[0]
  deals = Deal.objects.filter(bar = bar)
  list(deals)

  return direct_to_template(request, 'barManager/cuponManager.html',
        {'adminBar' : True,
         'deals' : deals,
         'bar' : bar})
  
  
